package com.hyz.config;

import com.hyz.filter.AccessDeniedHandlerImpl;
import com.hyz.filter.AuthenticationEntryPointImpl;
import com.hyz.filter.AuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author HGD
 * @date 2022/9/15 15:55
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    @Autowired
    private AuthenticationFilter authenticationFilter;
    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;
    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPointImpl;

    /**
     * 以后如果想要配置过滤器链，可以通过自定义 SecurityFilterChainBean 来实现。
     *
     * @param http 请求
     * @return 过滤器链
     * @throws Exception csrf关闭异常
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 这里是将自定义的过滤器放在了 Security 过滤器脸链的最前端
        http.addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class);

        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问。只能未登录访问 anonymous()
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        // 调整过滤器链 让异常过滤器是走我们自己创建的异常处理
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPointImpl)
                .accessDeniedHandler(accessDeniedHandler);

        // 允许跨域
        return http.build();
    }

    /**
     * 将 AuthenticationConfiguration 自动装载，获取对象 authenticationConfiguration
     * 通过 authenticationConfiguration 获取 AuthenticationManager 接口对象
     */
    @Autowired
    private AuthenticationConfiguration authenticationConfiguration;

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
}
